package com.wxming.quartzdemo.config;

import com.alibaba.druid.pool.DruidDataSource;//druid-1.1.5.jar
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author wxming.
 * @date 2018/1/12.
 */
@Configuration
@MapperScan(basePackages = MySqlDataSourceConfig.PACKAGE,sqlSessionFactoryRef = "mysqlSqlSessionFactory")
public class MySqlDataSourceConfig {
    static final String PACKAGE ="com.wxming.quartzdemo.mappers.mysql";

    @Value("${datasource.mysql.url}")
    private String url;
    @Value("${datasource.mysql.username}")
    private String user;
    @Value("${datasource.mysql.password}")
    private String password;
    @Value("${datasource.mysql.driver-class-name}")
    private String driverClassName;

    @Bean(name = "mysqlDataSource")
    @Primary
    public DataSource mysqlDataSource(){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(driverClassName);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(user);
        druidDataSource.setPassword(password);
        druidDataSource.setValidationQuery("SELECT 1 FROM DUAL");

        return druidDataSource;
    }

    @Bean(name = "mysqlTransactionManager")
    @Primary
    public DataSourceTransactionManager mysqlTransactionManager(){
        return new DataSourceTransactionManager(mysqlDataSource());
    }

    @Bean(name = "mysqlSqlSessionFactory")
    @Primary
    public SqlSessionFactory mysqlSqlSessionFactory(@Qualifier("mysqlDataSource") DataSource mysqlDataSource) throws Exception{
        final SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();

        org.apache.ibatis.session.Configuration config = new org.apache.ibatis.session.Configuration();
        config.setMapUnderscoreToCamelCase(true);
        config.setCallSettersOnNulls(true);
        sessionFactoryBean.setConfiguration(config);
        sessionFactoryBean.setDataSource(mysqlDataSource);
        return sessionFactoryBean.getObject();
    }

}
